package com.hyfrogx.modules.app.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyfrogx.common.utils.Constant;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author crazypenguin
 * @version 1.0.0
 * @createdate 2019/1/25
 */
public class WeChatUtils {

    public static String getAccessToken(String appid, String secret) {
        Map params = CollUtil.newHashMap();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("grant_type", "client_credential");
        return HttpUtil.get(Constant.WX_TOKEN_URL, params, 5000);
    }

    public static String getWXACodeUnlimit(String access_token, Map params) {
        String url = Constant.WXA_GETWXACODEUNLIMIT_URL + "?access_token=" + access_token;
        HttpResponse response = HttpRequest.post(url).body(JSON.toJSONString(params)).timeout(5000).charset("UTF-8").execute();
        if (JSONUtil.isJsonObj(response.body())) {
            return response.body();
        } else {
            return cn.hutool.core.codec.Base64.encode(response.bodyStream());
        }
    }

	public JSONObject getUserInfo(String encryptedData, String sessionkey, String iv){
        try {

            // 被加密的数据
            byte[] dataByte = Base64.decode(encryptedData);
            // 加密秘钥
            byte[] keyByte = Base64.decode(sessionkey);
            // 偏移量
            byte[] ivByte = Base64.decode(iv);

            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String  getToken() throws Exception{
//        String accessToken = HttpUtil.get(url);
//        JSONObject jsonObject = JSONObject.parseObject(accessToken);
//        return String.valueOf(jsonObject.get("access_token"));
//    }

    /**
     * 发送文本
     * @param openid
     * @param text
     * @param access_token
     * @return
     * @throws Exception
     */
    public static String sendKfMessage(String openid,String text,String access_token)throws Exception{
        Map<String,Object> map_content = new HashMap<>();
        map_content.put("content",text);
        Map<String,Object> map = new HashMap<>();
        map.put("touser",openid);
        map.put("msgtype","text");
        map.put("text",map_content);
        String content =  JSONObject.toJSONString(map);
        return HttpUtil.post(Constant.WX_KF_SEND+access_token,content);

    }

    /**
     * 发送图片
     * @param openid
     * @param mediaId
     * @param access_token
     * @return
     * @throws Exception
     */
    public static String sendKfImage(String openid, String mediaId, String access_token)throws Exception{
        Map<String,Object> map_content = new HashMap<>();
        map_content.put("media_id",mediaId);

        Map<String,Object> map = new HashMap<>();
        map.put("touser",openid);
        map.put("msgtype","image");
        map.put("image",map_content);
        String content =  JSONObject.toJSONString(map);
        return HttpUtil.post(Constant.WX_KF_SEND+access_token,content);
    }


    public static String sendKfLink(String openid,String title,String desc,String url,String thumb_url,String access_token)throws Exception{
        Map<String,Object> map_content = new HashMap<>();
        map_content.put("description",desc);
        map_content.put("title",title);
        map_content.put("url",url);
        map_content.put("thumb_url",thumb_url);

        Map<String,Object> map = new HashMap<>();
        map.put("touser",openid);
        map.put("msgtype","link");
        map.put("link",map_content);
        String content =  JSONObject.toJSONString(map);
        return HttpUtil.post(Constant.WX_KF_SEND+access_token,content);

    }

}
